package com.sdgakj.web.user;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Role;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumUserType;
import com.sdgakj.rest.UserLoginRestController;
import com.sdgakj.service.manager.RoleService;
import com.sdgakj.service.user.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "/user")
public class UserController {

	private static final String PAGE_SIZE = "10";

	private static Map<String,String> sortTypes =Maps.newLinkedHashMap();
	private static Logger logger = LoggerFactory.getLogger(UserLoginRestController.class);

	static {
		sortTypes.put("auto", "自动");
	}

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;
	/**
	 * 查询管理员列表
	 * @param pageNumber 页号
	 * @param pageSize   每页大小
	 * @param sortType   排序字段
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/admin",method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
			ServletRequest request) {
		Map<String,Object> searchParams =Servlets.getParametersStartingWith(request, "search_");

		Page<User> users =userService.getUsers("admin",searchParams,pageNumber,pageSize,sortType);

		model.addAttribute("users",users);
		model.addAttribute("sortType", sortType);
		model.addAttribute("sortTypes", sortTypes);
		// 将搜索条件编码成字符串，用于排序，分页的URL
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
   		return "user/userList";
	}

    /**
     * 查询管理员列表
     * @param pageNumber 页号
     * @param pageSize   每页大小
     * @param sortType   排序字段
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value="/list",method = RequestMethod.GET)
    public String userList(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
            @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
            ServletRequest request) {
        Map<String,Object> searchParams =Servlets.getParametersStartingWith(request, "search_");

        Page<User> users =userService.getUsers("normal",searchParams,pageNumber,pageSize,sortType);

        model.addAttribute("users",users);
        model.addAttribute("sortType", sortType);
        model.addAttribute("sortTypes", sortTypes);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "user/userList";
    }

	/**
	 * 跳转添加管理员页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="create",method=RequestMethod.GET)
	public String  create(Model model){
		List<Role> roleList =roleService.getAllRoles();
		model.addAttribute("roles", roleList);
		model.addAttribute("action", "create");
		return "user/userForm";
	}

	@RequestMapping(value="/create",method=RequestMethod.POST)
	public String createUser(User user,
			@RequestParam("roleid")Long roleid,RedirectAttributes redirectAttributes){
		logger.info("create the admin ...");
		if(!roleid.equals('0')){
			Role role =roleService.getRoleById(roleid);
			user.setRole(role);
		}
		 userService.saveUser(user);
		return "redirect:/user/admin";
	}

	/**
	 * 跳转修改管理员页面
	 * @return
	 */
	@RequestMapping(value="update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable("id") Long id, Model model){
		List<Role> roleList =roleService.getAllRoles();
		model.addAttribute("roles", roleList);
		model.addAttribute("user", userService.getUserById(id));
		model.addAttribute("action", "update");

		return "user/userForm";
	}
	/**
	 * 更新管理员用户信息
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String updateUser(@Valid @ModelAttribute("user") User user,
							 @RequestParam("roleid")Long roleid,RedirectAttributes redirectAttributes){
		logger.info("update the admin info...");
		if(!roleid.equals('0')){
			Role role =roleService.getRoleById(roleid);
			user.setRole(role);
		}
		userService.updateUser(user);
		redirectAttributes.addFlashAttribute("message", "更新用户信息成功");
		return "redirect:/user/admin";
	}

    /**
     * 更新管理员用户信息
     * @param user
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value="/jsp/login",method=RequestMethod.GET)
    public String userJsp(){
        return "app/user/user_login";
    }

	/**
	 * 修改当前管理员密码
	 * @param tel 电话
	 * @param pwd 密码
	 * @param code 验证码
	 * @return
	 */
	@RequestMapping(value = "/changeadminpwd", method = RequestMethod.POST)
	public String changeadminpwd(@RequestParam(value = "id", defaultValue = "0") Long id,
			@RequestParam(value = "plainPassword", defaultValue = "0") String pwd,RedirectAttributes redirectAttributes) {
		logger.info("edit admin password : " + id);
	    userService.changeAdminPwd(id, pwd);
		redirectAttributes.addFlashAttribute("message", "修改管理员密码成功，请重新登录！");
		return "redirect:/logout";
	}

	@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
	public String delete(@PathVariable("id") Long id,RedirectAttributes redirectAttributes){
		User user =userService.getUserById(id);
		user.setDeltag(EnumIsDelete.DELETED.getCode()); //设置已经删除
		userService.deleteUser(user);
		redirectAttributes.addFlashAttribute("message", "删除管理员信息成功！");
		return "redirect:/user/admin";
	}

	/**
	 * 重置管理员密码
	 * @param tel 电话
	 * @param pwd 密码
	 * @param code 验证码
	 * @return
	 */
	@RequestMapping(value = "/findadminpwd",method = RequestMethod.GET)
	public String findadminpwd(@RequestParam(value = "mobile", defaultValue = "0") String tel,
			@RequestParam(value = "plainPassword", defaultValue = "0") String pwd,
			@RequestParam(value = "code", defaultValue = "0") String code,RedirectAttributes redirectAttributes) {
		logger.info("tel : " + tel);
		// 验证短信校验码
	    userService.recoverAdminPwd(tel, pwd, code);
		redirectAttributes.addFlashAttribute("message", "重置管理员密码成功，请重新登录！");
		return "redirect:/login";
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.-
	 */
	@ModelAttribute
	public void getUser(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		if (id != -1) {
			model.addAttribute("user", userService.getUserById(id));
		}
	}

	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "checkLoginName")
	@ResponseBody
	public String checkLoginName(@RequestParam("loginName") String loginName,
			@RequestParam(value = "userId", defaultValue = "") String userId) {
		User user = null;
		if(StringUtils.isNotBlank(userId)){
			user = userService.getUserById(Long.valueOf(userId));
		}
		User checkuser = null;
		checkuser = userService.getUserByLoginName(loginName, EnumUserType.ADMIN.getCode());
		if (checkuser == null) {
			return "true";
		} else {
			if (user != null && checkuser.getLoginName().equals(user.getLoginName())) {
				return "true";
			}
			return "false";
		}
	}

	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "checkuserlogin")
	@ResponseBody
	public String checUserLogin(@RequestParam("loginName") String loginName,
			@RequestParam(value = "userId", defaultValue = "") String userId) {
		User user = null;
		if(StringUtils.isNotBlank(userId)){
			user = userService.getUserById(Long.valueOf(userId));
		}
		User checkuser = null;
		checkuser = userService.getUserByLoginName(loginName, EnumUserType.CUSTOMOR.getCode());
		if (checkuser == null) {
			return "false";
		} else {
			if (user != null && checkuser.getLoginName().equals(user.getLoginName())) {
				return "false";
			}
			return "true";
		}
	}

	/**
	 * Ajax请求校验checkTell是否唯一。
	 */
	@RequestMapping(value = "/checkmobile")
	@ResponseBody
	public String checkMobile(@RequestParam("mobile") String tell,
			@RequestParam(value = "userId", defaultValue = "") String userId) {
		User user = null;
		if(StringUtils.isNotBlank(userId)){
			user = userService.getUserById(Long.valueOf(userId));
		}
		User checkuser = null;
		checkuser = userService.getUserByTell(tell, EnumUserType.ADMIN.getCode());
		if (checkuser == null) {
			return "true";
		} else {
			if (user != null && checkuser.getMobile().equals(user.getMobile())) {
				return "true";
			}
			return "false";
		}
	}
	
	/**
	 * Ajax请求校验admin用户的电话是否唯一。
	 */
	@RequestMapping(value = "/checkadmintel")
	@ResponseBody
	public String checkAdminMobile(@RequestParam("mobile") String tell,
			@RequestParam(value = "userId", defaultValue = "") String userId) {
		User user = null;
		if(StringUtils.isNotBlank(userId)){
			user = userService.getUserById(Long.valueOf(userId));
		}
		User checkuser = null;
		checkuser = userService.getAdminByTell(tell, EnumUserType.ADMIN.getCode());
		if (checkuser == null) {
			return "true";
		} else {
			if (user != null && checkuser.getMobile().equals(user.getMobile())) {
				return "true";
			}
			return "false";
		}
	}
}
